import re
import logging

from django.shortcuts import render_to_response
from google.appengine.api import users

import models_common as models


###########################################################################################################################
def render(template, payload):
    '''render the template with payload'''
    return render_to_response(template, payload)

def logUserAccess(user):
    '''log the user access to data store'''
    usr = models.User.all().filter('user = ', user).get()
    if not usr:
        usr = models.User(user=user, access_count=1)
    else:
        if usr.access_count:
            usr.access_count = usr.access_count + 1
        else:
            usr.access_count = 1 + 1
        
    usr.put()

def getAllUsers():
    '''get all the users order by the last access'''
    return models.User.all().order('-last_update')

def getUser(email="anonymous@gmail.com"):
    '''get all the current user, if not exist, return anonymous'''
    user = users.get_current_user()
    if not user:
        user = users.User(email)
    logUserAccess(user)
    return user

def getLoginAndUrl(request):
    '''get toggled login and logout label and the url'''
    if users.get_current_user():
        url = users.create_logout_url(request.get_full_path())
        url_linktext = 'Logout'
    else:
        url = users.create_login_url(request.get_full_path())
        url_linktext = 'Login'
    return url_linktext, url

def logActivity():
    pass
    
###########################################################################################################################